package com.hktf.corelib.utils;

import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.res.ResourcesCompat;

import com.hktf.corelib.BaseApplication;
import com.hktf.corelib.R;
import com.hktf.corelib.constant.KEYS;
import com.hktf.corelib.eventBus.LoginEvent;
import com.hktf.corelib.jsonbean.UserDto;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommUtils {

    /**
     * dip to  px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px to dip
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {

        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 用于升级中，界面显示版本号，eg：001001002----->1.1.2
     *
     * @param version
     * @return
     */
    public static String getVersionFormat(String version) {
        if (version.length() == 7) {
            version = "00" + version;
        }
        String last = version.substring(6, 9);
        String middle = version.substring(3, 6);
        String first = version.substring(0, 3);
        String result = "";
        try {
            result = Integer.parseInt(first) + "." + Integer.parseInt(middle) + "."
                    + Integer.parseInt(last);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 从vdi版本信息中得到升级路径中的文件夹名称
     *
     * @return
     */
    public static String getVdiUpdateDir() {
        String updateDir = null;
        if (Config.VDI_VERSION != null) {
            try {
                String[] split = Config.VDI_VERSION.split("_V");
                updateDir = split[0];
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        LogMds.i("cdz", "updateDir=" + updateDir);
        return updateDir;
    }

    public static String getVdiVersion() {
        String version = Config.DEFAULT_VDI_VERSION;
        try {
            if (Config.VDI_VERSION != null) {
                String tempVersion = Config.VDI_VERSION;
                String tempVersion1 = "";
                //wupeng  修改VDI版本信息获取方式
                String[] split = Config.VDI_VERSION.split("_V");
                String[] split2 = split[1].split(" ");
                tempVersion = split2[0];
                tempVersion1 = split2[1];
                if (CommUtils.hasSpecialInspection() && tempVersion1.contains("_")) {
                    String[] arrayStrs = tempVersion1.split("_");
                    String[] array1 = arrayStrs[1].split("\\.");
                    String[] array = tempVersion.split("\\.");
                    if (array.length == 3 && array1.length == 3) {
                        String frist = String.format("%03d", Integer.parseInt(array[0]) + Integer.parseInt(array1[0]));
                        String second = String.format("%03d", Integer.parseInt(array[1]) + Integer.parseInt(array1[1]));
                        String last = array[2];
                        if (array[2].contains("T")) {
                            String[] split3 = array[2].split("T");
                            last = split3[0];
                        }
                        last = String.format("%03d", Integer.parseInt(last) + Integer.parseInt(array1[2]));
                        version = frist + second + last;
                    }
                } else {
                    String[] array = tempVersion.split("\\.");
                    if (array.length == 3) {
                        String frist = String.format("%03d", Integer.parseInt(array[0]));
                        String second = String.format("%03d", Integer.parseInt(array[1]));
                        String last = array[2];
                        if (array[2].contains("T")) {
                            String[] split3 = array[2].split("T");
                            last = split3[0];
                        }
                        last = String.format("%03d", Integer.parseInt(last));
                        version = frist + second + last;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public static String getPackageName(Context context) {
        PackageInfo info;
        String packageNames = null;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            // 当前应用的版本名称
            String versionName = info.versionName;
            // 当前版本的版本号
            int versionCode = info.versionCode;
            // 当前版本的包名
            packageNames = info.packageName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageNames;

    }

    public static Context getContext() {
        return BaseApplication.getContext();
    }

    /**
     * 提交主线程运行runnable
     *
     * @param runnable
     */
    public static void runOnUiThread(Runnable runnable) {
        if (android.os.Process.myTid() == BaseApplication.getMainTid()) {//如果主线程中运行
            runnable.run();
        } else {//如果子线程中运行
            //拿到主线程handler 执行post
            BaseApplication.getMainHandler().post(runnable);
        }

    }

    public static void mainHandlerpost(Runnable runnable) {
        BaseApplication.getMainHandler().post(runnable);

    }

    /**
     * 获取res
     *
     * @return
     */
    public static Resources getResources() {
        return getContext().getResources();
    }

    /**
     * 切换键盘状态
     *
     * @param v
     */
    public static void switchInput(View v) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 打开键盘
     *
     * @param v
     */
    public static void openInput(View v) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 关闭键盘
     *
     * @param v
     */
    public static void closeInput(View v) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 强制隐藏键盘
    }

    public static Drawable getDrawable(int resid) {
        return getResources().getDrawable(resid);
    }

    public static boolean isRunMainUIThread() {
        return android.os.Process.myTid() == BaseApplication.getMainTid();
    }

    public static String getString(int res) {
        return getResources().getString(res);
    }

    public static View inflate(int layout) {
        return LayoutInflater.from(getContext()).inflate(layout, null);
    }

    public static String[] getStringArray(int res) {

        return getResources().getStringArray(res);
    }

    /**
     * 0   1
     *
     * @param context
     * @return
     */
    //得到屏幕旋转的状态
    public static int getRotationStatus(Context context) {
        int status = 0;
        try {
            status = android.provider.Settings.System.getInt(context.getContentResolver(),
                    android.provider.Settings.System.ACCELEROMETER_ROTATION);
            if (status == 0) {
                setRotationStatus(context.getContentResolver(), 1);
            }
        } catch (Settings.SettingNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return status;
    }

    public static void setRotationStatus(ContentResolver resolver, int status) {
        //得到uri
        Uri uri = android.provider.Settings.System.getUriFor("accelerometer_rotation");
        //沟通设置status的值改变屏幕旋转设置
        android.provider.Settings.System.putInt(resolver, "accelerometer_rotation", status);
        //通知改变
        resolver.notifyChange(uri, null);
    }

    /**
     * 如果配置Ox10 0X10 截取  16-10  如果没有OX 默认为10进制
     */
    public static int parse16To10(String result) throws Exception {
        if (TextUtils.isEmpty(result)) {
            return -1;
        }
        result = result.toUpperCase();
        if (result.contains("0X")) {
            return Integer.valueOf(result.substring(2, result.length()), 16);
        }
        return Integer.parseInt(result);
    }

    /**
     * 是否开启区域限销功能
     *
     * @return
     */
    public static boolean hasLocationLimit() {
        return "true".equals(getResources().getString(R.string.has_location_limit));
    }

    /**
     * 是否开启注册流程优化
     *
     * @return
     */
    public static boolean isNeedEMail() {
        return !("YDS-C80-Android".equals(Config.CLIENTNAME) || "YDS-C80-EN-Android".equals(Config.CLIENTNAME) || "YDS-T100-Android".equals(Config.CLIENTNAME) || "YDS-B80-Android".equals(Config.CLIENTNAME) || "YDS-B80-EN-Android".equals(Config.CLIENTNAME)
                || "YDS-B80-BOGELI-Android".equals(Config.CLIENTNAME) || "YDS-B80-YOULIBO-Android".equals(Config.CLIENTNAME) || "YDS-C80E-Android".equals(Config.CLIENTNAME) || "YDS-B90-Android".equals(Config.CLIENTNAME) || "YDS-B80PRO-Android".equals(Config.CLIENTNAME)
                || "YDS-D80-BOGELI-Android".equals(Config.CLIENTNAME) || "YDS-D60-HCXY-Android".equals(Config.CLIENTNAME) || "YDS-D60-JM-Android".equals(Config.CLIENTNAME)
                || "YDS-D60-YQDK-Android".equals(Config.CLIENTNAME) || "YDS-D60-SDKM-Android".equals(Config.CLIENTNAME) || "YDS-D60-QYQC-Android".equals(Config.CLIENTNAME)
                || "YDS-D60-QICHE-Android".equals(Config.CLIENTNAME) || "YDS-C20-Android".equals(Config.CLIENTNAME) || "YDS-C81-Android".equals(Config.CLIENTNAME) || "YDS-C60-Android".equals(Config.CLIENTNAME)
                || "YDS-C90-Android".equals(Config.CLIENTNAME) || "YDS-C90-AREA-Android".equals(Config.CLIENTNAME) || "D60-Huafengdongli-Android".equals(Config.CLIENTNAME) || "YDS-D60-KAIMAOIL-ANDROID".equals(Config.CLIENTNAME));
    }

    /**
     * 是否开启注册流程优化
     *
     * @return
     */
    public static boolean isNewRegister() {
        return "true".equals(getResources().getString(R.string.new_register));
    }

    /**
     * 是否显示默认ecu刷写文件夹
     *
     * @return
     */
    public static boolean isShowDefaultEcufilepath() {
        return "true".equals(getResources().getString(R.string.show_default_ecufilepath));
    }

    /**
     * 是否有分期功能
     *
     * @return
     */
    public static boolean isInstallment() {
        return "true".equals(getResources().getString(R.string.is_installment));
    }

    /**
     * 是否配置项目盒子是否支持升级专检
     *
     * @return
     */
    public static boolean hasSpecialInspection() {
        return "true".equals(getResources().getString(R.string.vdi_specialinspection));
    }

    /**
     * 是否需要连接盒子
     *
     * @return
     */
    public static boolean withoutVdi() {
        //        return false;
        return "true".equals(getResources().getString(R.string.without_vdi));
    }
    /**
     * 是否支持usb连接方式
     *
     * @return
     */
    public static boolean hasUsb() {
        //        return false;
        return "true".equals(getResources().getString(R.string.hasusb));
    }

    /**
     * 是否配置项目专检购买方式是部分购买false还是全部购买true
     *
     * @return
     */
    public static boolean isSpecialInspectionBuyAll() {
        return "true".equals(getResources().getString(R.string.vdi_specialinspection_buy_all));
    }

    /**
     * 是否横屏
     *
     * @return
     */
    public static boolean getOrientationConfig() {
        return "true".equals(getResources().getString(R.string.islandscape));
    }

    /**
     * 获取已经开通的专检项
     *
     * @param s 传入专检比特位字符串例如111110000
     * @return
     */
    public static String getSpecialInspection(String s) {
        String[] stringArray = getContext().getResources().getStringArray(R.array.specialinspection);
        int length = stringArray.length - 1;
        String[] split = s.split(",");
        String intStr = "";
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < split.length; i++) {
            String str = split[i];
            if (str.equals("1")) {
                LogMds.i("cdz1", "i=" + i + "...length=" + length);
                if (i < (length)) {
                    intStr = stringArray[i].split(",")[1];
                    if (stringBuffer.toString().contains(intStr)) {
                        continue;
                    } else {
                        stringBuffer.append(intStr + ",");
                    }
                }
            }
        }
        String[] split1 = stringBuffer.toString().split(",");
        int len = split1.length;
        for (int i = 0; i < len - 1; i++) {
            for (int j = 0; j < len - 1 - i; j++) {
                if (Integer.valueOf(split1[j]) > Integer.valueOf(split1[j + 1])) {        // 相邻元素两两对比
                    String temp = split1[j + 1];        // 元素交换
                    split1[j + 1] = split1[j];
                    split1[j] = temp;
                }
            }
        }
        String result = "";
        for (String s1 : split1) {
            result += s1;
        }
        return result;
    }

    public static void resetDongliyh() {
        Config.DECRYPTRESULT = null;
        Config.ecu_model = null;
    }

    public static boolean isVdiConnect() {
        try {
            if (((BaseApplication) getContext()).isBluetoothConn() || ((BaseApplication) getContext()).isUsbConn() || CommUtils.withoutVdi()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

    public static boolean checkTelphone(String tel) {
        boolean result = false;
        if (tel != null && tel.length() == 11) {
            // 校验 手机11位
            Pattern mobilep = Pattern
                    .compile("((^(11|12|13|14|15|16|17|19|18)[0-9]{9}$))");
            Matcher mobilem = mobilep.matcher(tel);
            if (!mobilem.matches()) {
                result = false;
            } else {
                result = true;
            }
        } else {
            result = false;
        }
        return result;
    }

    /**
     * 判读vin客串是否合法
     *
     * @param vin
     */
    public static boolean isVaildVin(String vin) {
        boolean result = true;
        if (vin.length() != 17) {
            result = false;
        } else {
            String upVin = vin.toUpperCase();
            for (int i = 0; i < upVin.length(); i++) {
                char c = upVin.charAt(i);
                if ((c < '0' || c > '9') && (c < 'A' || c > 'Z')) {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 获取当前app版本号
     *
     * @return
     */
    public static String getCurrentAppVersion() {
        String versionCode = "";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = getContext().getPackageManager().getPackageInfo(
                    getContext().getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;

    }

    /**
     * 将内容复制到剪切板
     * @param content
     * @param context
     */
    public static void copy(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content);
        Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
    }






    public static boolean isMiNiSn(){
        if (Config.SN == null) {
            return false;
        }
        if(Config.SN.contains("YXVDISM")){
            return true;
        }
        return false;
    }

    public static int getmConnectStatus() {
        BaseApplication context = null;
        try {
            context = (BaseApplication) BaseApplication.getContext();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (context == null) {
            return 0;
        }
        return context.getmConnectStatus();
    }

    public static boolean isInstall(String packageName) {
        final PackageManager packageManager = getContext().getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        LogMds.e("wei", "...........................pinfo size=" + pinfo.size());
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                LogMds.i("wei", "...........................pn=" + pn);
                if (pn.contains(packageName)) {
                    LogMds.e("wei", "...........................pn=" + pn);
                    return true;
                }
            }
        }
        return false;
    }

    public static void saveUserInfo(UserDto userDto){
        //如果用户信息中没有token,就获取本地保存的用户信息中的token
        String token = userDto.getToken();
        if(token==null){
            UserDto localUser=MMKVUtils.getObj(KEYS.USERINFO, UserDto.class);
            if(localUser!=null){
                userDto.setToken(localUser.getToken());
            }
        }
        Config.USERINFO=userDto;
        LogMds.e("cdz", "...........................saveUserInfo=" + GsonUtils.createGsonString(userDto));
        LogMds.e("cdz","user token="+userDto.getToken());
        MMKVUtils.putObj(KEYS.USERINFO, Config.USERINFO);
        EventBus.getDefault().post(new LoginEvent(LoginEvent.CHANGE_USERINFO));
    }
    public static UserDto getUserInfo(){
        Config.USERINFO=MMKVUtils.getObj(KEYS.USERINFO, UserDto.class);
        return Config.USERINFO;
    }
    public static String getHiddenPhone(String phone){
        if (phone==null) {
            return "";
        }
        if (phone.length()<11) {
            return phone;
        }
        return phone.substring(0,3)+"****"+phone.substring(7);
    }
    public static String getHiddenName(String phone){
        if (phone == null||"".equals(phone)) {
            return null;
        }
        if (phone.length()<2) {
            return phone;
        }
        if (phone.length()==2) {
            return phone.substring(0,1)+"*";
        }
        return phone.substring(0,2)+"*";
    }

    public static void setfont(Context context,TextView tv,int fondId){
        tv.setTypeface(ResourcesCompat.getFont(context,fondId));
    }
    public static void userLogout(){
        MMKVUtils.removeKey(KEYS.USERINFO);
//        MMKVUtils.removeKey(KEYS.ASSISTANT_LIST);
        Config.USERINFO=null;
    }
    public static boolean isLogin(){
        return Config.USERINFO!=null;
    }

    public static void setText(TextView tv,String text){
        if (tv == null||text==null) {
            return;
        }
        tv.setText(text);
    }

}
